// 设置pinia的user管理
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { getToken, setToken, removeToken } from '@/utils/storage'
import { login, logout } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 将获得的token赋值给pinia的token
  const token = ref(getToken() || '')
  const UserInfo = reactive({})

  const setTokenPinia = (newToken) => {
    token.value = newToken
    // 同时将token 存到浏览器的localStorage
    setToken(newToken)
  }

  const clearTokenPinia = () => {
    token.value = ''
    removeToken()
  }

  const setUserInfoPinia = (info) => {
    // 安全的设置userInfo对象
    Object.assign(UserInfo, info)
  }

  // 清除用户信息但是保留token
  const clearUserInfoPinia = () => {
    Object.assign(UserInfo, {})
  }

  // 登录发送请求的方法 接收一个表单数据loginadmin
  const loginActions = async (loginForm) => {
    try {
      const res = await login(loginForm)
      // 如果拿到结果 先将token存起来 (包括pinia的浏览器的)
      setTokenPinia(res.data.token)
      // 返回响应
      return { success: true, data: res }
    } catch (error) {
      return { success: false, data: error }
    }
  }
  const logoutActions = async () => {
    try {
      const res = await logout()
      // 一起清除token(pinia和浏览器的)
      clearTokenPinia()
      return { success: true, data: res }
    } catch (error) {
      // 即使是登出失败 也要清除token
      clearTokenPinia()
      return { success: false, data: error }
    }
}
  return {
    token,
    UserInfo,
    setTokenPinia,
    clearTokenPinia,
    setUserInfoPinia,
    clearUserInfoPinia,
    loginActions,
    logoutActions,
  };
})
